<route lang="yaml">
meta:
  title: 监测数据
</route>

<script setup>
import axios from 'axios'
import { onMounted, ref } from 'vue'

const searchSerial = ref('')
const selectedUnit = ref('')
const currentPage = ref('1')
const pageSize = ref(2)

const totalUnits = ref(100)
const totalDevices = ref(0)
const devices = ref([])
const customerCode = ref('') // 选中单位的 customerCode
const curCustomer = ref('') // 选中单位的 customerCode

const units = ref([])

// 通用请求函数，用于分页和查询
async function fetchData() {
  console.log('参数', customerCode.value)
  const params = {
    customerCode: customerCode.value,
    // deviceSerial: searchSerial.value,
    customerUnitid: '1',
    pageNum: currentPage.value,
    pageSize: pageSize.value,
  }
  if (customerCode.value === '000000') {
    totalDevices.value = 0
    devices.value = []
  }
  else {
    try {
      const response = await axios.post('https://www.cqwuyang.cn/ElectricManageService/hik/business/queryDeviceList', params)
      console.log('返回数据', response.data)
      totalDevices.value = response.data.data.total
      devices.value = response.data.data.rows
    }
    catch (error) {
      console.error('请求失败:', error)
    }
  }
}

// 从 localStorage 获取用户区域
const adminUserRegion = localStorage.getItem('adminUserRegion')

// 获取单位数据的函数
async function fetchCustomerData() {
  try {
    const params = {
      // customerRegion: adminUserRegion,
      pageNum: '1',
      customerState: -1,
      pageSize: '100',
    }

    // 发起 POST 请求
    const response = await axios.post('https://www.cqwuyang.cn/ElectricManageService/customer/findAllByCondition', params)
    // 将单位数据填充到下拉框中
    units.value = response.data.data.rows
    if (units.value.length > 0) {
      // selectedUnit.value = units.value[0].customerName // 默认选中第一个单位名称
      customerCode.value = units.value[0].customerCode // 设置对应的单位代码
      console.log('所有单位:', units.value)
      console.log('默认选中的单位:', selectedUnit.value)
      console.log('默认选中的单位代码:', customerCode.value)
    }
  }
  catch (error) {
    console.error('获取单位数据失败:', error)
  }
}

// 用户选择单位时的回调函数
function handleUnitChange(selectedCustomerName) {
  const selectedUnit = units.value.find(item => item.customerName === selectedCustomerName)
  if (selectedUnit) {
    customerCode.value = selectedUnit.customerCode // 设置 customerCode
    curCustomer.value = selectedUnit
    console.log('选中的单位代码:', customerCode.value)
    console.log('选中的单位，', curCustomer)
  }
}

const router = useRouter()
function openMonitorPage(row) {
  console.log(row)
  const to = router.resolve({
    name: 'monitor-details',
    params: { id: row },
    query: { data: JSON.stringify(row) }, // 将对象转换为 JSON 字符串
  })
  const httpUrl = to.href.replace(/^https:\/\//, 'http://')
  window.open(httpUrl, '_blank')
  // window.open(to.href, '_blank')
}

// 点击“搜索”按钮时触发查询
function handleSearch() {
  if (curCustomer.value.customerUnitid === '' || curCustomer.value.customerUnitid === '000000') {
    console.log('数据为空')
    customerCode.value = '000000'
  }
  currentPage.value = 1 // 重置到第一页
  fetchData()
}

onMounted(async () => {
  await fetchCustomerData() // 等待 fetchCustomerData 完成
  await fetchData()// 然后执行 fetchData
})
</script>

<template>
  <div class="device-dashboard">
    <!-- 左侧搜索区域 -->
    <div class="sidebar">
      <el-input v-model="searchSerial" placeholder="请输入设备序列号" clearable />
      <el-select v-model="selectedUnit" placeholder="请选择单位" class="mt-4" @change="handleUnitChange">
        <!-- 下拉选项显示 customerName -->
        <el-option
          v-for="unit in units" :key="unit.customerCode" :label="unit.customerName"
          :value="unit.customerName"
        />
      </el-select>
      <el-button type="primary" class="mt-4" @click="handleSearch">
        搜索
      </el-button>
    </div>

    <!-- 主内容区域 -->
    <div class="content">
      <!-- 数量信息 -->
      <div class="device-info">
        <!-- <div class="info-item">
          <div class="circle">{{ totalUnits }}</div>
          <p>单位数量</p>
        </div> -->
        <div class="info-item">
          <div class="circle">
            {{ totalDevices }}
          </div>
          <p>设备数量</p>
        </div>
      </div>

      <!-- 设备列表 -->
      <el-card v-for="(device, index) in devices" :key="index" class="device-card" @click="openMonitorPage(device)">
        <div class="device-header">
          <h4>{{ device.deviceName }}</h4>
          <el-tag v-if="device.deviceStatus === '在线'" type="success">
            在线
          </el-tag>
          <el-tag v-if="device.unitStatus === '正常'" type="info">
            正常
          </el-tag>
        </div>
        <p>详细地址：{{ device.location }}</p>
        <p>序列号：{{ device.deviceSerial }}</p>
        <p>设备类型：{{ device.deviceType }}</p>
        <p>设备型号：{{ device.deviceModel }}</p>
      </el-card>

      <!-- 分页 -->
      <el-pagination
        v-model:current-page="currentPage" v-model:page-size="pageSize" class="pagination" background
        :default-page-size="pageSize" layout="prev, pager, next" :total="totalDevices" @current-change="fetchData"
        @size-change="fetchData"
      />
    </div>
  </div>
</template>

<style scoped>
.device-dashboard {
  display: flex;
}

.sidebar {
  width: 20%;
  padding: 20px;
  border-right: 1px solid #ebebeb;
}

.content {
  width: 80%;
  padding: 20px;
}

.device-info {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.info-item {
  text-align: center;
}

.circle {
  width: 80px;
  height: 80px;
  margin: 0 auto;
  font-size: 24px;
  font-weight: bold;
  line-height: 80px;
  background-color: #bab9b9;
  border-radius: 50%;
}

.device-card {
  margin-bottom: 20px;
}

.device-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 10px;
}

.pagination {
  margin-top: 20px;
  text-align: center;
}
</style>
